package com.chenjj.java.mq.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.chenjj.java.business.order.OrderInfoVO;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * 路由模式的生产者
 */
public class OrderProviderRouting {
    private Logger logger = LoggerFactory.getLogger(OrderProviderRouting.class);

    private String defaultUri = "amqp://cjj:cjj@localhost:5672/vhost_cjj";

    private ConnectionFactory connectionFactory = new ConnectionFactory();

    public OrderProviderRouting() throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
        connectionFactory.setUri(defaultUri);
    }

    public OrderProviderRouting(String uri) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException {
        connectionFactory.setUri(uri);
    }

    /**
     * 将orderInfo 发送到MQ
     * @param orderInfoVO
     */
    public void sendOrderInfo(OrderInfoVO orderInfoVO){
        String exchangeName = "orderInfoExchangeDirect";
        String routeKey_VIP = "vip"; //vip 消费金额大于5000的同时发邮件和短信提醒
        String routeKey_NORMAL = "normal"; //normal 消费金额小于5000的只发短信

        Connection connection = null;
        Channel channel = null;
        try{
            String orderInfoStr = JSONUtil.parse(orderInfoVO).toString();
            byte [] orderInfoByte = orderInfoStr.getBytes("UTF-8");

            System.out.println("Publish message: " + orderInfoStr);

            connection = connectionFactory.newConnection();
            channel = connection.createChannel();

            //和简单队列不同的是，生产者不会直接往队列发送消息，而是往exchange发送消息。
            //声明一个direct类型的、持久化的exchange
            channel.exchangeDeclare(exchangeName,"direct",true,false,null);

            //发布消息(持久化消息)
            if (orderInfoVO.getMoney() >= 5000){
                channel.basicPublish(exchangeName,routeKey_VIP,MessageProperties.PERSISTENT_TEXT_PLAIN,orderInfoByte);
            }else{
                channel.basicPublish(exchangeName,routeKey_NORMAL,MessageProperties.PERSISTENT_TEXT_PLAIN,orderInfoByte);
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("",e);
        }finally {
            releaseResource(connection,channel);
        }
    }

    private void releaseResource(Connection connection,Channel channel){
        if (channel!=null){
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
